package com.zjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjl.common.R;
import com.zjl.entity.Employee;
import com.zjl.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping(value = "/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     *
     * @param request
     *          用于将员工id保存在session中
     * @param employee
     * @return
     */
    @PostMapping(value = "/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
//        1.密码md5加密
        String password = employee.getPassword();
        password=DigestUtils.md5DigestAsHex(password.getBytes());
//        2.根据用户名查询用户
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<Employee>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
//        3.用户判空
        if (emp==null){
            return  R.error("登录失败");
        }
//        4.密码匹配
        if (!password.equals(emp.getPassword())){
            return R.error("密码错误");
        }
//        5.查询员工状态
        if (emp.getStatus()==0){
//            被禁用
            return  R.error("该账户被禁用");
        }
//        6.成功登录,员工id放入session
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出，清理session中的employee的id
     * @param request
     * @return
     */
    @PostMapping(value = "/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> addEmp(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工信息：{}",employee.toString());
//        设置初始密码123456，md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
////        设置创建时间
//        employee.setCreateTime(LocalDateTime.now());
////        设置更新时间
//        employee.setUpdateTime(LocalDateTime.now());
//        设置创建人与更新人，从session中得到id
//        Long empId = (Long)request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

//      将员工信息保存
        employeeService.save(employee);
        return R.success("保存成功");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping(value = "/page")
    public R<Page> page(int page,int pageSize,String name){
        //        log.info("page={},pageSize={},name={}",page,pageSize,name);

        //构造分页构造器
        Page<Employee> employeePage=new Page<Employee>(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();

        //添加过滤条件,StringUtils.isNotEmpty令name即使为空也不会报错，程序继续执行。
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getUsername,name);

        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询,结果集封装在employeePage中
        employeeService.page(employeePage,queryWrapper);
        log.info("Total={}",employeePage.getTotal());
        return R.success(employeePage);
    }

    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpServletRequest request){
//        log.info("emp:{}",employee.toString());
//        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long)request.getSession().getAttribute("employee"));
        employeeService.updateById(employee);
        long id = Thread.currentThread().getId();
        log.info("当前线程id：{}",id);
        return R.success("修改成功");
    }

    /**
     * 员工数据回显
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee emp = employeeService.getById(id);
        if (emp==null)
            return R.error("没有查询到该用户");
        return R.success(emp);
    }
}
